// pages/joinRoom/joinRoom.js
const app = getApp()

Page({
  data: {
    room: "",
    disable: true,
    opacity: 0.6,
  },

  roomInput: function(res) {
    this.setData({
      room: res.detail.value,
      disable: res.detail.value.length <= 0,
      opacity: res.detail.value.length <= 0 ? 0.6: 1.0,
    })
  },

  joinRoom: async function () {
    var that = this
    if (this.data.disable) return
    wx.showLoading({
      title: '加入中...',
    })
    const db = wx.cloud.database();
    db.collection("room").doc(this.data.room).get({
      success: function (res) {
        console.log('[云数据库] [room] 查询: ', res)
        wx.hideLoading()
        if (res.data.length <= 0) {
          wx.showToast({
            title: '查找不到当前房间号',
            icon: 'none',
          })
        } else {
          that.sendJoinMessage()
        }
      },
      fail: function (res) {
        console.log('[云数据库] [room] 查询失败: ', res)
        wx.hideLoading()
        wx.showToast({
          title: '查找不到当前房间号',
          icon: 'none',
        })
      }
    })
  },

  sendJoinMessage: async function () {
    var that = this
    const db = wx.cloud.database();
    db.collection("message").add({
      data: {
        room: this.data.room,
        sender: app.globalData.openid,
        msgType: "command-join",
        msgContent: app.globalData.userInfo.nickName + "  加入房间",
        nickname: app.globalData.userInfo.nickName,
        avatar: app.globalData.userInfo.avatarUrl,
        sendTime: new Date(),
        sendTimeTS: Date.now()
      },
      success: function (res) {
        console.log('[云数据库] [message] 插入: ', res)
        wx.hideLoading()
        that.changeUserStatus()
      },
      fail: function (res) {
        console.log('[云数据库] [message] 插入失败: ', res)
        wx.hideLoading()
        wx.showToast({
          title: '加入房间失败，请重试',
          icon: 'none',
        })
      }
    })
  },

  changeUserStatus: async function() {
    var that = this
    wx.cloud.callFunction({
      name: "modifyUser",
      data: {
        status: "ready",
        room: this.data.room,
        solve: false,
      },
      success: function (res) {
        console.log('[云数据库] [user] 更新: ', res)
        wx.hideLoading()
        wx.reLaunch({
          url: '../startGame/startGame?room=' + that.data.room
        })
      },
      fail: function (res) {
        console.log('[云数据库] [user] 更新失败: ', res)
        wx.hideLoading()
        wx.showToast({
          title: '加入房间失败，请重试',
          icon: 'none',
        })
      }
    })
  }
})